

#if defined (ESP8266)
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <WiFiClientSecure.h>
#endif

#if defined(ESP32)
#include <WiFi.h>
#include <HTTPClient.h>
#include <WiFiClientSecure.h>
#endif

#include <ArduinoJson.h>

//测试HTTPS通讯的网站
const char *host = "restapi.amap.com";
//HTTPS端口443
const int httpsPort = 443;


//高德API获取实时天气
void GetWeatherLive() {

  WiFiClientSecure httpsClient;    //建立WiFiClientSecure对象
  Serial.println(host);
  httpsClient.setInsecure();
  httpsClient.setTimeout(100);
  httpsClient.setBufferSizes(2048, 512); // 语法httpsClient.setBufferSizes(recv, xmit);参数recv：接收缓存大小，该数值大小必须介于512和16384之间（单位字节，类型：int）xmit：发送缓存大小，该数值大小必须介于512和16384之间（单位字节，类型：int）

  Serial.println("HTTPS Connecting"); Serial.println("");
  int r = 0; // 尝试连接服务器并等待
  while ((!httpsClient.connect(host, httpsPort)) && (r < 30)) {
    delay(100);
    Serial.print(".");
    r++;
  }
  // 连接超时后输出"连接失败"信息并返回
  if (r == 30) {
    Serial.println("Connection failed");
    return;
  } else { // 连接成功则输出“连接成功”信息
    Serial.println("Connected...");
  }

  Serial.print("requesting: ");
  Serial.println(host);

  // 建立HTTPS请求信息字符串
  String reqRes = "/v3/weather/weatherInfo?city=" + citycode + "&key=" + key + "&extensions=base";
  String request =  String("GET ") + reqRes + " HTTP/1.1\r\n" +
                    "Host: " + host + "\r\n" +
                    "Connection: close\r\n" +
                    "\r\n";
  // 向服务器发送请求
  httpsClient.print(request);

  Serial.println("request sent");

  // 检查服务器响应信息。一旦查到响应头结束字符，则通过串口监视器
  // 告知用户当前ESP8266已经成功接收服务器响应头信息。
  while (httpsClient.connected()) {
    String line = httpsClient.readStringUntil('\n');
    if (line == "\r") {
      Serial.println("headers received");
      break;
    }
  }

  // 通过串口监视器输出服务器响应体信息（服务器报文）
  //  Serial.println("==========");
  //  Serial.println("server response payload:");
  String line;
  while (httpsClient.available()) {
    line = httpsClient.readStringUntil('\n');  //Read Line by Line
    //Serial.println(line); //Print response
  }
  //  Serial.println("==========");

  //操作结束，断开服务器连接
  httpsClient.stop();
  Serial.println("closing connection");

  DynamicJsonDocument  jsonBuffer(768);//实时天气768，预报2048,----->>>>>计算：  https://arduinojson.org/v6/assistant/
  DeserializationError error = deserializeJson(jsonBuffer, line);
  if (error)
  {
    Serial.print("天气实况加载json配置失败:");
    Serial.println(error.f_str());
    //return false;
  }
  else {
    Serial.println("天气实况加载json配置成功");
  }
  if (jsonBuffer["status"].isNull() == 0) {//检查到不为空
    if (jsonBuffer["status"] == "1" && jsonBuffer["infocode"] == "10000") {
      JsonObject lives_0 = jsonBuffer["lives"][0];//0表示第一个大括号内容
      //      String weatherlive = jsonBuffer["lives"][0]["weather"];
      //      String temlive = lives_0["temperature"];
      String reporttime = lives_0["reporttime"];
      //      Serial.println(reporttime);
      //reporttime: 2023-06-18 07:02:43
      r_year = reporttime.substring(0, 4).toInt();
      r_month = reporttime.substring(5, 7).toInt();
      r_day = reporttime.substring(8, 10).toInt();
      r_hour = reporttime.substring(11, 13).toInt();
      //      Serial.print(r_year); Serial.print(r_month); Serial.println(r_day);

      //数据给结构体，不加as<>会报错
      WeatherLive.weather = lives_0["weather"].as<String>();
      WeatherLive.temperature = lives_0["temperature"].as<int>();
      WeatherLive.winddirection = lives_0["winddirection"].as<String>();
      WeatherLive.windpower = lives_0["windpower"].as<String>();
      WeatherLive.humidity = lives_0["humidity"].as<String>();

    }
  }
}

void GetWeatherForcast() {

  WiFiClientSecure httpsClient;    //建立WiFiClientSecure对象
  Serial.println(host);
  httpsClient.setInsecure();
  httpsClient.setTimeout(100);
  httpsClient.setBufferSizes(2048, 512); // 语法httpsClient.setBufferSizes(recv, xmit);参数recv：接收缓存大小，该数值大小必须介于512和16384之间（单位字节，类型：int）xmit：发送缓存大小，该数值大小必须介于512和16384之间（单位字节，类型：int）
  Serial.println("HTTPS Connecting"); Serial.println("");
  int r = 0; // 尝试连接服务器并等待
  while ((!httpsClient.connect(host, httpsPort)) && (r < 30)) {
    delay(100);
    Serial.print(".");
    r++;
  }
  // 连接超时后输出"连接失败"信息并返回
  if (r == 30) {
    Serial.println("Connection failed");
    return;
  } else { // 连接成功则输出“连接成功”信息
    Serial.println("Connected...");
  }

  Serial.print("requesting: ");
  Serial.println(host);

  // 建立HTTPS请求信息字符串
  String reqRes = "/v3/weather/weatherInfo?city=" + citycode + "&key=" + key + "&extensions=all";
  String request =  String("GET ") + reqRes + " HTTP/1.1\r\n" +
                    "Host: " + host + "\r\n" +
                    "Connection: close\r\n" +
                    "\r\n";
  // 向服务器发送请求
  httpsClient.print(request);

  Serial.println("request sent");

  // 检查服务器响应信息。一旦查到响应头结束字符，则通过串口监视器
  // 告知用户当前ESP8266已经成功接收服务器响应头信息。
  while (httpsClient.connected()) {
    String line = httpsClient.readStringUntil('\n');
    if (line == "\r") {
      Serial.println("headers received");
      break;
    }
  }

  // 通过串口监视器输出服务器响应体信息（服务器报文）
  Serial.println("==========");
  Serial.println("server response payload:");
  String line;
  while (httpsClient.available()) {
    line = httpsClient.readStringUntil('\n');  //Read Line by Line
    //Serial.println(line); //Print response
  }
  Serial.println("==========");

  //操作结束，断开服务器连接
  httpsClient.stop();
  Serial.println("closing connection");

  DynamicJsonDocument  jsonBuffer(1536);//实时天气768，预报2048,----->>>>>计算：  https://arduinojson.org/v6/assistant/
  DeserializationError error = deserializeJson(jsonBuffer, line);
  if (error)
  {
    Serial.print("天气预报加载json配置失败:");
    Serial.println(error.f_str());
    //return false;
  }
  else {
    Serial.println("天气预报加载json配置成功");
  }
  if (jsonBuffer["status"].isNull() == 0) {//检查到不为空
    if (jsonBuffer["status"] == "1" && jsonBuffer["infocode"] == "10000") {

      //这句不好使
      //      String casts_0_dayweather = jsonBuffer["forcasts"][0]["casts"][0]["dayweather"].as<String>();

      JsonObject forecasts_0 = jsonBuffer["forecasts"][0];
      JsonObject casts_0 = forecasts_0["casts"][0];//当日天气预报
      
      Forcasts_0.dayweather = casts_0["dayweather"].as<String>();
      Forcasts_0.nightweather = casts_0["nightweather"].as<String>();
      Forcasts_0.daytemp = casts_0["daytemp"].as<String>();
      Forcasts_0.nighttemp = casts_0["nighttemp"].as<String>();


    }
  }
}
